package com.zhj.common.web.log;

import org.slf4j.MDC;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.GenericApplicationListener;
import org.springframework.core.Ordered;
import org.springframework.core.ResolvableType;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils;

/**
 * @author zhj
 */
public class LogMDCListener implements GenericApplicationListener {

    private static final String APPLICATION_CONFIG_NAME = "configurationProperties";
    private static final String LOG_NAME = "logging.file.name";
    private static final String LOG_PATH = "spring.application.name";

    /**
     * 设置监听什么类型的事件
     * @param resolvableType
     * @return
     */
    @Override
    public boolean supportsEventType(ResolvableType resolvableType) {
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(resolvableType.getRawClass());
    }

    /**
     * 监听到具体事件的处理方法
     * @param applicationEvent
     */
    @Override
    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        System.out.println("接收Spring事件广播" + applicationEvent);
        ApplicationEnvironmentPreparedEvent event = (ApplicationEnvironmentPreparedEvent) applicationEvent;
        ConfigurableEnvironment environment = event.getEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        PropertySource<?> propertySource = propertySources.get(APPLICATION_CONFIG_NAME);
        String logName = (String) propertySource.getProperty(LOG_NAME);
        String logPath = (String) propertySource.getProperty(LOG_PATH);
        if (StringUtils.isEmpty(logName)) {
            logName = logPath;
        }
        System.out.println("获取到logName: " + logName + " ,logPath: " + logPath);
        MDC.put("logName", logName);
        MDC.put("logPath", logPath);
        System.out.println("MDC装载logName和logPath完成");
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 19;
    }
}
